import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Field;
import jdk.internal.vm.Continuation;
import jdk.internal.vm.ContinuationScope;
import sun.misc.Unsafe;

// java --enable-preview --add-opens java.base/jdk.internal.vm=ALL-UNNAMED Loom3
@SuppressWarnings("deprecation")
public class Loom3 {
	private static final ContinuationScope cs = new ContinuationScope("VirtualThreads");
	private static final Unsafe U;
	private static final long CONT_OFFSET;
	//	private static final long MOUNTED_OFFSET;
	private static final MethodHandle DO_YIELD;
	private static final MethodHandle ENTER_SPECIAL;
//	private static final MethodHandle SET_EXTENT_LOCAL_CACHE;

	static {
		try {
			Field theUnsafeField = Unsafe.class.getDeclaredField("theUnsafe");
			theUnsafeField.setAccessible(true);
			U = (Unsafe)theUnsafeField.get(null);
			long OVERRIDE_OFFSET;
			for (long i = 8; ; i++) {
				if (U.getBoolean(theUnsafeField, i)) {
					theUnsafeField.setAccessible(false);
					if (!U.getBoolean(theUnsafeField, i)) {
						OVERRIDE_OFFSET = i;
						break;
					}
					theUnsafeField.setAccessible(true);
				}
				if (i == 32) // should be enough
					throw new UnsupportedOperationException(System.getProperty("java.version"));
			}

			var f = Thread.class.getDeclaredField("cont");
			U.putBoolean(f, OVERRIDE_OFFSET, true); // f.setAccessible(true);
			CONT_OFFSET = U.objectFieldOffset(f);
//			f = Continuation.class.getDeclaredField("mounted");
//			U.putBoolean(f, OVERRIDE_OFFSET, true); // f.setAccessible(true);
//			MOUNTED_OFFSET = U.objectFieldOffset(f);
			var m = Continuation.class.getDeclaredMethod("doYield");
			U.putBoolean(m, OVERRIDE_OFFSET, true);
			DO_YIELD = MethodHandles.lookup().unreflect(m);
			m = Continuation.class.getDeclaredMethod("enterSpecial", Continuation.class, boolean.class, boolean.class);
			U.putBoolean(m, OVERRIDE_OFFSET, true);
			ENTER_SPECIAL = MethodHandles.lookup().unreflect(m);
//			m = Thread.class.getDeclaredMethod("setExtentLocalCache", Object[].class);
//			U.putBoolean(m, OVERRIDE_OFFSET, true);
//			SET_EXTENT_LOCAL_CACHE = MethodHandles.lookup().unreflect(m);
		} catch (ReflectiveOperationException e) {
			throw new RuntimeException(e);
		}
	}

	static Continuation start(Runnable r) {
		var c = new Continuation(cs, r);
		c.run();
//		try {
//			U.putBooleanVolatile(c, MOUNTED_OFFSET, true);
//			SET_EXTENT_LOCAL_CACHE.invokeExact((Object[])null);
//			U.putObject(Thread.currentThread(), CONT_OFFSET, c);
//			ENTER_SPECIAL.invokeExact(c, false, false);
//		} catch (Throwable e) {
//			throw new RuntimeException(e);
//		}
		return c;
	}

	static void pause() {
		var c = U.getObject(Thread.currentThread(), CONT_OFFSET);
		try {
			@SuppressWarnings("unused")
			var __ = (int)DO_YIELD.invokeExact();
			U.storeFence(); // needed to prevent certain transformations by the compiler
		} catch (Throwable e) {
			throw new RuntimeException(e);
		} finally {
			U.putObject(Thread.currentThread(), CONT_OFFSET, c);
		}
	}

	static void resume(Continuation c) {
		if (c.isDone())
			throw new IllegalStateException("Continuation terminated");
		try {
			ENTER_SPECIAL.invokeExact(c, true, false);
		} catch (Throwable e) {
			throw new RuntimeException(e);
		}
	}

	private static void test(int i) {
		System.out.println("begin " + i);
		var c1 = start(() -> {
			System.out.println("before pause1: " + U.getObject(Thread.currentThread(), CONT_OFFSET));
			pause();
			System.out.println("after pause1: " + U.getObject(Thread.currentThread(), CONT_OFFSET));
		});
		var c2 = start(() -> {
			System.out.println("before pause2: " + U.getObject(Thread.currentThread(), CONT_OFFSET));
			pause();
			System.out.println("after pause2: " + U.getObject(Thread.currentThread(), CONT_OFFSET));
		});
		System.out.println("resume1");
		resume(c1);
		System.out.println("resume2");
		resume(c2);
		System.out.println("end");
	}

	public static void main(String[] args) throws InterruptedException {
		for (int i = 0; i < 1000; i++)
			test(i);
	}
}
